<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <treeIndex
          :deptOptions="deptOptions"
          @handleNode="handleNodeClick"
          :title="'组织数据'"
          :defaultProps="{
            children: 'childList',
            label: 'name',
          }"
        ></treeIndex>
      </el-col>
      <el-col :span="20" :xs="24">
        <searchForm
          :formOptions="formOptions"
          @onSearch="onSearch"
          @onReset="onReset"
          v-show="showSearch"
        >
        <el-form-item label="所在院部：">
            <!-- <el-cascader v-model="queryParams.deptId" :options="deptOptions" style="width: 200px"
              :props="{ value: 'id', currentLabels: 'label', checkStrictly: true }" @change="handleChange"></el-cascader> -->
            <el-select v-model="queryParams.deptId" placeholder="请选择" clearable class="elSelect" @change="handleChange"
              style="width: 100%">
              <el-option v-for="item in collegeSelectList" :key="item.deptId" :label="item.deptName"
                :value="item.deptId"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所选专业：">
            <el-select v-model="queryParams.specialityId" clearable placeholder="请选择" style="width: 200px">
              <el-option v-for="item in profession" :key="item.VALUE" :label="item.TITILE"
                :value="item.VALUE"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所在年级：">
            <el-select v-model="queryParams.gradeId" clearable placeholder="请选择" style="width: 200px">
              <el-option v-for="item in gradeDate" :key="item.VALUE" :label="item.TITILE"
                :value="item.VALUE"></el-option>
            </el-select>
          </el-form-item>
        </searchForm>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" v-hasPermi="[addBtnPremission]">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              >新增成员（学生）</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
                  <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增成员（老师）</el-button>
              </el-col> -->
          <el-col :span="1.5" v-hasPermi="[delBtnPremission]">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="plHandleDelete"
              >退出组织</el-button
            >
          </el-col>
          <el-col :span="1.5" v-hasPermi="[exportBtnPremission]">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              >导出</el-button
            >
          </el-col>
          <el-col :span="1.5" v-hasPermi="[importBtnPremission]">
            <el-button
              type="warning"
              plain
              size="mini"
              @click="downloadTemplate"
              >下载导入模板</el-button
            >
          </el-col>
          <el-col :span="1.5" v-hasPermi="[importBtnPremission]">
            <el-upload
              class="upload-demo"
              :action="uploadAction"
              :headers="uploadHeaders"
              accept=".xlsx"
              :show-file-list="false"
              :on-success="onSuccess"
              :multiple="false"
            >
              <el-button type="warning" plain icon="el-icon-upload2" size="mini"
                >导入</el-button
              >
            </el-upload>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
          ></right-toolbar>
        </el-row>
        <el-table
          :data="tablelist"
          @selection-change="handleSelectionChange"
          v-if="!stringDate"
          key="456"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="学号"
            prop="registerCode"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column label="姓名" prop="stuName" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="studentDetail(scope.row)">{{
                scope.row.stuName
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="sex" align="center">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_user_sex"
                :value="scope.row.sex"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="身份证号"
            prop="cardCode"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="学院"
            prop="deptNames"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="所属团支部"
            v-if="!stringDate"
            :show-overflow-tooltip="true"
            prop="orgId"
            align="center"
          >
            <template slot-scope="scope">
              {{ scope.row.orgId | getOrgName(organList) }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="所属团支部"
            v-if="isStudentClub"
            prop="unionName"
            :show-overflow-tooltip="true"
            align="center"
          ></el-table-column> -->
          <el-table-column
            label="政治面貌"
            prop="political"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.bc_political_type"
                :value="scope.row.political"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="年级"
            prop="gradeName"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="班级信息"
            prop="className"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="入团时间"
            prop="joinDate"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="毕业时间"
            prop="guaduateDate"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="是否录入智慧团建"
            width="120"
            prop="isBuilding"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.follow_status"
                :value="scope.row.isBuilding"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="发展团员编号"
            width="120"
            prop="memberCode"
            :show-overflow-tooltip="true"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="是否注册志愿者"
            prop="isVolunteer"
            :show-overflow-tooltip="true"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.follow_status"
                :value="scope.row.isVolunteer"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="志愿者服务时长"
            prop="volunteerTime"
            :show-overflow-tooltip="true"
            width="120"
            align="center"
          >
            <template slot-scope="scope">
              {{
                scope.row.volunteerTime ? scope.row.volunteerTime + "小时" : ""
              }}
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="150"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="[editBtnPremission]"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="[delBtnPremission]"
                @click="handleDelete([scope.row.id])"
                >退出</el-button
              >
              <!-- <el-button size="mini" type="text"  @click="handleDelete(scope.row)">设为组织负责人</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <el-table
          :data="tablelist"
          @selection-change="handleSelectionChange" key="123"
          v-if="stringDate"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column
            label="学号"
            prop="registerCode"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column label="姓名" prop="stuName" align="center">
            <template slot-scope="scope">
              <el-button type="text" @click="studentDetail(scope.row)">{{
                scope.row.stuName
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="sex" align="center">
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.sys_user_sex"
                :value="scope.row.sex"
              ></dict-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="学院"
            prop="deptNames"
            :show-overflow-tooltip="true"
            align="center"
          /><el-table-column
            label="班级信息"
            prop="className"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="政治面貌"
            prop="political"
            :show-overflow-tooltip="true"
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :options="dict.type.bc_political_type"
                :value="scope.row.political"
              ></dict-tag>
            </template>
          </el-table-column>
          <el-table-column
            label="联系方式"
            prop="stuMobile"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="辅导员姓名"
            prop="clrName"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            label="辅导员电话"
            prop="clrMobile"
            :show-overflow-tooltip="true"
            align="center"
          />
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="150"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                v-hasPermi="[editBtnPremission]"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                v-hasPermi="[delBtnPremission]"
                @click="handleDelete([scope.row.id])"
                >退出</el-button
              >
              <!-- <el-button size="mini" type="text"  @click="handleDelete(scope.row)">设为组织负责人</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <Add
      ref="addRef"
      :treeData="deptOptions"
      @updateList="getList"
      :isCommittee="isCommittee"
      :isStudentClub="isStudentClub"
    ></Add>
    <StudentList ref="studentListRef" @addUser="addUser"></StudentList>
    <studentInfors
      ref="saveDialog"
      :deptOptions="collegeSelectList"
      :title="title"
      showType="detail"
      :forms="form"
    >
    </studentInfors>
  </div>
</template>
  <script>
var downloadLoadingInstance = null;
import searchForm from "@/components/Search/searchForm.vue";
import treeIndex from "@/components/tree/index.vue";
import {
  organizeTree,
  organizeList,
  studentOrganizeList,
} from "@/api/leagueManagement/organize";
import {
  organizeUserList,
  delOrganizeUser,
  organizeUserTemplate,
  clubOrganizeUserList,
  delClubOrganizeUser,
  cluborganizeUserTemplate,
} from "@/api/leagueManagement/organizeUser";
import { studentInfor, collegeSelect } from "@/api/information/studentInfor";
import Add from "./moudles/addDlg.vue";
import StudentList from "./moudles/studentList";
import { Loading } from "element-ui";
import errorCode from "@/utils/errorCode";
import { tansParams, blobValidate, handleTree } from "@/utils/util";
import { getToken } from "@/utils/auth";
import { saveAs } from "file-saver";
import studentInfors from "@/views/components/student/index";
import { getSpecialityByDeptId } from "@/api/information/unitMajor";
import { getGradeSelect } from "@/api/information/gradeInfor";


export default {
  components: {
    treeIndex,
    searchForm,
    Add,
    StudentList,
    studentInfors,
  },
  dicts: ["sys_user_sex", "bc_political_type", "follow_status"],
  data() {
    return {
      deptOptions: [],
      organList: [],
      formOptions: [
        {
            label: "学号",
            prop: "registerCode",
            element: "el-input",
            placeholder: "请输入学号",
        },
        {
          label: "姓名",
          prop: "stuName",
          element: "el-input",
          placeholder: "请输入姓名",
        },
      ],
      showSearch: true,
      tablelist: [],
      selectData: [],
      profession: [],
      stringDate: "", // 校团委
      total: 0,
      queryParams: {
        pageNum: 0,
        pageSize: 10,
        name: "",
      },
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      form: {},
      title: "",
      collegeSelectList: [],
      gradeDate: []
    };
  },
  watch: {},
  computed: {
    isCommittee() {
      return this.$route.query.type == "committee";
    },
    isStudentClub() {
      return this.$route.query.type == "studentClub";
    },
    uploadAction() {
      if (this.$route.query.type == "committee") {
        return process.env.VUE_APP_BASE_API + "/league/org/user/importUser";
      }
      if (this.$route.query.type == "studentClub") {
        return process.env.VUE_APP_BASE_API + "/league/union/user/importUser";
      }
    },
    addBtnPremission() {
      if (this.isCommittee) {
        return "tuanCommittee:committeeUser:add";
      }
      if (this.isStudentClub) {
        return "tuanCommittee:studentClubUser:add";
      }
    },
    exportBtnPremission() {
      if (this.isCommittee) {
        return "tuanCommittee:committeeUser:export";
      }
      if (this.isStudentClub) {
        return "tuanCommittee:studentClubUser:export";
      }
    },
    importBtnPremission() {
      if (this.isCommittee) {
        return "tuanCommittee:committeeUser:import";
      }
      if (this.isStudentClub) {
        return "tuanCommittee:studentClubUser:import";
      }
    },
    editBtnPremission() {
      if (this.isCommittee) {
        return "tuanCommittee:committeeUser:edit";
      }
      if (this.isStudentClub) {
        return "tuanCommittee:studentClubUser:edit";
      }
    },
    delBtnPremission() {
      if (this.isCommittee) {
        return "tuanCommittee:committeeUser:del";
      }
      if (this.isStudentClub) {
        return "tuanCommittee:studentClubUser:del";
      }
    },
  },
  created() {
    this.getOrganizeTree();
    this.getList();
    collegeSelect().then(res => {
        this.collegeSelectList = res.data;
      });
      this.getGradeInfor()
  },
  methods: {
     // 下拉树选择
     handleChange(value) {
      this.form.deptId = value;
      this.queryParams.deptId = value;
      this.form.specialityId = "";
      this.getSpeciality();
    },
      // 查询所在年级
      getGradeInfor() {
      getGradeSelect().then(response => {
        // console.log(response, "Student");
        this.gradeDate = response.data;
      });
    },
      // 查找专业
      getSpeciality() {
      if (this.form.deptId) {
        getSpecialityByDeptId({ deptId: this.form.deptId }).then(res => {
          if (res.code == "200") {
            this.profession = res.data;
          } else {
            console.log("123");
            this.profession = [];
          }
        });
      } else {
        this.profession = [];
      }
    },
    async studentDetail(row) {
      const roleId = row.stuId;
      Promise.all([collegeSelect(), studentInfor(roleId)]).then((resArr) => {
        this.collegeSelectList = resArr[0].data;
        console.log(this.collegeSelectList,'所属部门')
        this.form = resArr[1].data;
        this.$refs.saveDialog.openDia();
        this.title = "学生信息";
      });
    },
    //文件上传成功
    onSuccess(response) {
      if (response.code == 200) {
        this.$message.success(
          `导入成功：${response.data.successSize},导入失败：${response.data.errorSize}`
        );
        if (response.url) {
          window.open(process.env.VUE_APP_BASE_API + response.url);
        }
        this.getList();
      } else {
        this.$message.error(response.msg);
      }
    },
    downloadTemplate() {
      downloadLoadingInstance = Loading.service({
        text: "正在下载数据，请稍候",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.isCommittee) {
        organizeUserTemplate().then(async (data) => {
          const isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            saveAs(blob, `组织成员导入模版_${new Date().getTime()}.xlsx`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            this.$message.error(errMsg);
          }
          downloadLoadingInstance.close();
        });
      }
      if (this.isStudentClub) {
        cluborganizeUserTemplate().then(async (data) => {
          const isBlob = blobValidate(data);
          if (isBlob) {
            const blob = new Blob([data], {
              type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            saveAs(blob, `社团组织成员导入模版_${new Date().getTime()}.xlsx`);
          } else {
            const resText = await data.text();
            const rspObj = JSON.parse(resText);
            const errMsg =
              errorCode[rspObj.code] || rspObj.msg || errorCode["default"];
            this.$message.error(errMsg);
          }
          downloadLoadingInstance.close();
        });
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.isCommittee) {
        this.download(
          "/league/org/user/export",
          {
            ...this.queryParams,
          },
          `组织成员_${new Date().getTime()}.xlsx`
        );
      }
      if (this.isStudentClub) {
        this.download(
          "/league/union/user/export",
          {
            ...this.queryParams,
          },
          `社团组织成员_${new Date().getTime()}.xlsx`
        );
      }
    },
    handleAdd() {
      this.$refs.studentListRef.open();
    },
    addUser(rowdata) {
      this.$refs.addRef.open(rowdata, "add");
    },
    handleSelectionChange(val) {
      console.log(val, "val");
      this.selectData = val;
    },
    handleUpdate(rowdata) {
      if (this.isStudentClub) {
        rowdata.orgId = rowdata.unionId;
      }
      this.$refs.addRef.open(rowdata, "edit");
    },
    plHandleDelete() {
      if (this.selectData.length > 0) {
        this.handleDelete(
          this.selectData.map((item) => {
            return item.id;
          })
        );
      } else {
        this.$modal.msgWarning("请选择人员");
      }
    },
    handleDelete(ids) {
      this.$modal
        .confirm(`确认退出吗？`)
        .then(() => {
          if (this.isCommittee) {
            return delOrganizeUser(ids.join(","));
          }
          if (this.isStudentClub) {
            return delClubOrganizeUser(ids.join(","));
          }
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("退出成功");
        })
        .catch(() => {});
    },
    getOrganizeTree() {
      if (this.isCommittee) {
        organizeTree().then((res) => {
          if (Array.isArray(res)) {
            this.deleteEmpty(res);
            this.deptOptions = res;
          }
        });
      }

      if (this.isStudentClub) {
        studentOrganizeList().then((res) => {
          this.deptOptions = handleTree(
            res.rows,
            "id",
            "parentId",
            "childList"
          );
        });
      }

      organizeList().then((res) => {
        this.organList = res.rows;
      });
    },
    deleteEmpty(data) {
      data.forEach((element) => {
        if (element.childList) {
          if (element.childList.length > 0) {
            this.deleteEmpty(element.childList);
          } else {
            delete element.childList;
          }
        }
      });
    },
    getList() {
      if (this.isCommittee) {
        organizeUserList(this.queryParams).then((res) => {
          this.tablelist = res.rows;
          this.total = res.total;
        });
      }
      if (this.isStudentClub) {
        clubOrganizeUserList(this.queryParams).then((res) => {
          this.tablelist = res.rows;
          this.total = res.total;
        });
      }
    },
    handleNodeClick(data) {
      console.log(data, "左侧");
      this.stringDate = "";
      if (data.introduction.substr(0, 3) == "校团委") {
        this.stringDate = data.introduction.substr(0, 3);
      }
      this.queryParams.orgId = data.id;
      this.getList();
    },
    onSearch(val) {
      // 查询条件和分页数据合并
      const arr = Object.assign(this.queryParams, val);
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    onReset(data) {
      this.queryParams.pageNum = 1;
      const arr = Object.assign(this.queryParams, data);
      this.getList();
    },
  },
  filters: {
    getOrgName(text, arr) {
      if (text && arr) {
        const orgRowData = arr.find((item) => {
          return item.id == text;
        });
        if (orgRowData) {
          return orgRowData.name;
        } else {
          return "";
        }
      }
    },
  },
};
</script>
  <style scoped lang="scss">
.head-container {
  overflow-x: scroll;
}
</style>